package com.qk.mangement.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.JwtUtils;
import com.qk.domain.user.UserDO;
import com.qk.dto.user.UserDTO;
import com.qk.dto.user.UserLoginDTO;
import com.qk.entity.Role;
import com.qk.entity.User;
import com.qk.mangement.mapper.RoleMapper;
import com.qk.mangement.mapper.UserMapper;
import com.qk.mangement.service.UserService;
import com.qk.vo.user.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * 用户服务实现类
 */
@Service
@SuppressWarnings("all")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    private static final String DEFAULT_PASSWORD_SUFIX = "123";

    private static final Integer USER_STATUS_UNNORMAL = 0;

    @Override
    public List<User> listByRole(String roleLabel) {
        Role role = roleMapper.selectByLabel(roleLabel);
        if (ObjectUtils.isEmpty(role)) {
            throw new RuntimeException("角色不存在");
        }
        return userMapper.selectByRoleId(role.getId());
    }

    @Override
    public UserLoginVO login(UserLoginDTO dto) {
        boolean hasNull = BeanUtil.hasNullField(dto);
        if (hasNull) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        User dbUser=userMapper.selectByUsername(dto.getUsername());
        if(Objects.isNull(dbUser)){
            CommonException.throwCommonException(ParamEnum.LOGIN_USERNAME_ERROR);
        }
        if (ObjectUtil.equals(dbUser.getStatus(), USER_STATUS_UNNORMAL)){
            CommonException.throwCommonException(ParamEnum.LOGIN_STATUS_ERROR);
        }
        String userPassword = DigestUtils.md5DigestAsHex(dto.getPassword().getBytes());
        String encodedPassword = dbUser.getPassword();
        boolean isChecked = ObjectUtil.equals(encodedPassword, userPassword);
        if(!isChecked){
            CommonException.throwCommonException(ParamEnum.LOGIN_PASSWPRD_ERROR);
        }
        Role role = roleMapper.selectById(dbUser.getRoleId());
        //生成令牌中需要携带的自定义信息
        HashMap<String , Object> claims = new HashMap<>();
        claims.put("id", dbUser.getId());
        claims.put("username", dbUser.getUsername());
        return UserLoginVO.builder()
                .id(dbUser.getId())
                .username(dbUser.getUsername())
                .name(dbUser.getName())
                .image(dbUser.getImage())
                .roleLabel(role.getLabel())
                .token(JwtUtils.generateToken(claims))
                .build();
    }




    @Override
    public void deleteById(List<Integer> ids) {
        boolean isNotEmpty = CollectionUtil.isNotEmpty(ids);
        if (!isNotEmpty){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        userMapper.deleteBatch(ids);
    }

    @Override
    public void update(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateById(user);
    }

    @Override
    public User getById(Integer id) {
        if (Objects.isNull(id)){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        return userMapper.selectById(id);
    }




    @Override
    public void addUser(User user) {


        boolean hasNUll = BeanUtil.hasNullField(user,
                "id", "password", "roleId", "deptId", "image", "remark", "updateTime", "createTime");
        if (hasNUll) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }

        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        String rawPassword = new StringBuilder(user.getUsername()).append(DEFAULT_PASSWORD_SUFIX).toString();
        String encodedPassword = DigestUtils.md5DigestAsHex(rawPassword.getBytes());
        user.setPassword(encodedPassword);
        userMapper.insert(user);
    }

    /**
     * 条件分页查询用户列表
     */
    @Override
    public PageResult<UserDO> list(UserDTO dto) {

        PageHelper.startPage(dto.getPage(), dto.getPageSize());

        List<UserDO> users = userMapper.selectByPage(dto);

        Page<UserDO> page = (Page<UserDO>) users;

        PageResult<UserDO> pageResult = PageResult.<UserDO>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
        return pageResult;


    }


}